import TableActions from "@/components/TableActions";
import TableContainer from "@/components/TableContainer"
import { PAGINATION_CONFIG } from "@/constants";
import { CategoryState, CategoryType } from "@/constants/enums/category";
import { queryCategory, removeCategory, saveCategory } from "@/services/common";
import { enum2options } from "@/utils/enum2options";
import { PlusCircleFilled } from "@ant-design/icons";
import { styled } from "@umijs/max";
import { Access } from "@umijs/max";
import { useRequest } from "ahooks";
import { Button, Col, Form, Input, InputNumber, Modal, Popconfirm, Row, Select, Space, Spin, Table, message } from "antd"
import { ColumnsType } from "antd/es/table";
import { useState } from "react";

const OrderInput = styled.div`
  width: 100px;
  height: 32px;
  border-radius: 8px;

  &:hover {
    border: 1px solid #d9d9d9;
  }
`

const SortOrder: React.FC<{data: Category}> = ({data}) => {
  const [order, setOrder] = useState<number | null>(data.categoryOrder)
  const saveReq = useRequest(saveCategory, {manual: true})

  const save = () => {
    saveReq.run({...data, categoryOrder: order || 0})
  }

  return <OrderInput>
    <Spin spinning={saveReq.loading}>
      <InputNumber
        value={order} precision={0} controls={false} style={{width: '100%'}} variant="borderless"
        onChange={setOrder}
        onBlur={save}
        onPressEnter={save}
      />
    </Spin>
  </OrderInput>
}

const Device: React.FC = () => {
  const [searchForm] = Form.useForm()
  const [searchParams, setSearchParams] = useState<{state?: CategoryState, type?: CategoryType}>({
    type: CategoryType.积分商城,
  })
  const categoryList = useRequest(() => queryCategory(searchParams), {
    refreshDeps: [searchParams],
    // onSuccess: res => {
    //   categoryList.mutate({
    //     ...res,
    //     data: res.data.map(item => ({...item, children: item.subCategory.length ? item.subCategory : undefined}))
    //   })
    // }
  })
  const saveReq = useRequest(saveCategory, {manual: true})
  const delCategory = useRequest(removeCategory, {manual: true})

  const onFinish = (values: any) => {
    setSearchParams({
      ...searchParams,
      state: values.state,
    })
  }
  const delGroup = (record: Category) => {
    return delCategory.runAsync({categoryId: record.categoryId}).then(categoryList.refresh)
  }
  const disableGroup = (record: Category) => {
    return saveReq.runAsync({...record, categoryState: CategoryState.禁用}).then(categoryList.refresh)
  }
  const enableGroup = (record: Category) => {
    return saveReq.runAsync({...record, categoryState: CategoryState.启用}).then(categoryList.refresh)
  }
  const addGroup = () => {
    let valueName = ''
    Modal.confirm({
      icon: <PlusCircleFilled />,
      title: '新建分组',
      content: <Input placeholder="分组名称" onChange={({target}) => valueName = target.value} maxLength={20} />,
      onOk: async () => {
        valueName = valueName.trim()
        if (!valueName) {
          message.error('请输入有效的分组名称')
          return Promise.reject()
        }
        return saveReq.runAsync({
          categoryName: valueName, 
          categoryState: CategoryState.启用,
          categoryOrder: 0,
          businessType: CategoryType.积分商城,
        }).then(categoryList.refresh)
      }
    })
  }
  const addSubGroup = (record: Category) => {
    let valueName = ''
    Modal.confirm({
      icon: <PlusCircleFilled />,
      title: '新建子分组',
      content: <Input placeholder="子分组名称" onChange={({target}) => valueName = target.value} maxLength={20} />,
      onOk: async () => {
        valueName = valueName.trim()
        if (!valueName) {
          message.error('请输入有效的子分组名称')
          return Promise.reject()
        }
        return saveReq.runAsync({
          parentId: record.categoryId,
          categoryName: valueName, 
          categoryState: CategoryState.启用,
          categoryOrder: 0,
          businessType: CategoryType.积分商城,
        }).then(categoryList.refresh)
      }
    })
  }
  const editGroup = (record: Category) => {
    let valueName = ''
    Modal.confirm({
      icon: <PlusCircleFilled />,
      title: record.parentId ? '编辑子分组' : '编辑分组',
      content: <Input
        defaultValue={record.categoryName}
        placeholder={record.parentId ? '子分组名称' : '分组名称'}
        onChange={({target}) => valueName = target.value} maxLength={20}
      />,
      onOk: async () => {
        valueName = valueName.trim()
        if (!valueName) {
          message.error(`请输入有效的${record.parentId ? '子' : ''}分组名称`)
          return Promise.reject()
        }
        return saveReq.runAsync({...record, categoryName: valueName}).then(categoryList.refresh)
      }
    })
  }

  const columns: ColumnsType<Category> = [
    {
      title: '分组名称',
      dataIndex: 'categoryName',
    },
    {
      title: '分组状态',
      dataIndex: 'categoryState',
      render: val => {
        switch (val) {
          case CategoryState.启用: return '启用'
          case CategoryState.禁用: return '禁用'
          default: return '--'
        }
      }
    },
    {
      title: '权重',
      dataIndex: 'categoryOrder',
      width: 120,
      render: (categoryOrder, record) => <SortOrder data={record} />
    },
    {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      width: 220,
      render: (_, record) => {
        return (
          <TableActions>
            <Access accessible={!record.parentId && false}>
              <a onClick={() => addSubGroup(record)}>新建子分组</a>
            </Access>
            <Access accessible={record.categoryState === CategoryState.启用}>
              <Popconfirm
                title='确认禁用该分组吗？'
                onConfirm={async () => disableGroup(record)}
              >
                <a>禁用</a>
              </Popconfirm>
            </Access>
            <Access accessible={record.categoryState === CategoryState.禁用}>
              <Popconfirm
                title='确认启用该分组吗？'
                onConfirm={async () => enableGroup(record)}
              >
                <a>启用</a>
              </Popconfirm>
            </Access>
            <a onClick={() => editGroup(record)}>编辑</a>
            <Popconfirm
              title='确认删除该分组吗？'
              onConfirm={async () => delGroup(record)}
            >
              <a>删除</a>
            </Popconfirm>
          </TableActions>
        )
      }
    },
  ]
  
  return (
    <TableContainer>
      <TableContainer.Toolbar>
        <Button type='primary' onClick={addGroup}>新建分组</Button>
      </TableContainer.Toolbar>
      <TableContainer.SearchContainer>
        <Form colon={false} name='searchStationListForm' form={searchForm} onFinish={onFinish}>
          <Row gutter={[20, 20]}>
            <Col span={6}>
              <Form.Item label='分组状态' name='state'>
                <Select placeholder='请选择' variant='borderless' options={enum2options(CategoryState)} />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Space>
                <Button type='primary' htmlType='submit' loading={categoryList.loading}>筛选</Button>
                <Button htmlType='reset'>重置</Button>
              </Space>
            </Col>
          </Row>
        </Form>
      </TableContainer.SearchContainer>
      <Table<Category>
        rowKey='categoryId'
        loading={categoryList.loading}
        dataSource={categoryList.data?.data}
        columns={columns}
        scroll={{y: 700, x: 'max-content'}}
        pagination={{
          ...PAGINATION_CONFIG,
          pageSize: 10,
          showSizeChanger: false,
          total: categoryList.data?.totalCount || 0,
        }}
      />
    </TableContainer>
  )
}

export default Device
